function Add-OrchToList ($orchName, $orchList, $app)
{
	# check depended orchestrations
	if (-not ($orchList -contains "$orchName"))
	{
		foreach ( $childOrch in $app.orchestrations[$orchName].InvokedOrchestrations)
		{
			[array]$OrchList = Add-OrchToList $childOrch.FullName $orchList $app
		}
		# all depended orchestrations are in the list
		[array]$orchList += $orchName 
	}
	return $orchList
}

function Build-OrchestrationList ($server, $BizTalkApp, $app, $xmlBindings)
{
	#log-message "--- Unenlisting orchestrations on $server --" 
	$orchItems = get-wmiobject -class "MSBTS_Orchestration" -namespace "root\MicrosoftBizTalkServer" -computername $server

	foreach ($module in $xmlBindings.BindingInfo.ModuleRefCollection.ModuleRef)
	{
		foreach ($service in $module.services.service)
		{
			foreach ($objItem in $orchItems)
			{
				if ( $objItem -ne $null )
				{
					if ( $service.name -eq $objItem.Name )
					{
						$orchName = $objItem.Name
						[array]$objItemArray = Add-OrchToList $orchName $objItemArray $app
					}
				}
			}
		}
	}
	
	return $objItemArray
}

function UnEnlist-Orchestrations($orchItems, $server)
{
	#reverse array when unenlisting
	$orchItems = $orchItems[($orchItems.count - 1)..0] 
	foreach ($item in $orchItems)
	{
		$orchItem = get-wmiobject -class "MSBTS_Orchestration" -namespace "root\MicrosoftBizTalkServer" -computername $server -Filter "Name like '$item'" 
		if ( $orchItem -ne $null -and $orchItem.status -ne 2)
		{
				$msg = "Unlist $($orchItem.Name)" 
				if (Should-Process $msg ([REF]$AllAnswer) "" -Verbose:$Verbose -Confirm:$Confirm -Whatif:$Whatif)
				{	
				  Log-Message $msg -ForegroundColor green
					ReTry "UnEnlist Orchestration" {
					$orchItem.UnEnlist(2)
					} -AllowSkip #-ShowStatus

				}
		} 
	}
}

function Enlist-Orchestrations()
{
	# need enlist  orchestrations func
	#write-host 'Starting orchestrations one by one'

	#$list = BuildOrchList
	#$list = $list.substring(1)
	#$array = $list.Split(",")

	#For($i=0; $i -lt $array.count; $i++)
	#{
	#	$filter = $array[$i]
	#	$filter = "name= '$filter'"
	#	$orchItem = get-wmiobject -class "MSBTS_Orchestration" -namespace "root\MicrosoftBizTalkServer" -computername $strComputer -filter $filter
	#
	#	If ( $orchItem -ne $null -and $orchItem.status -ne 4)
	#       {
	#               write-host 'enlist ' $orchItem.Name -fore Green
	#		$orchItem.Enlist()
	#		write-host 'start ' $orchItem.Name -fore Green
	#               $orchItem.Start(2, 2, 2)
	#      	}     
	#}
}